<template>
  <el-card shadow="never">
    <el-tree
      :data="menuTreeList"
      show-checkbox
      default-expand-all
      node-key="id"
      :props="defaultProps"
      ref="tree"
    ></el-tree>
    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleClear">清空</el-button>
    </div>
  </el-card>
</template>

<script>
import {
  getLeftMenuAll,
  getRoleMenuWithId,
  editRoleMenuWithId,
} from "../../../api/adminApi";
export default {
  data() {
    return {
      menuTreeList: [], // 树形组件的数据源
      roleId: null,
      defaultProps: {
        label: "title",
        children: "children",
      },
    };
  },
  created() {
    this.treeList();
    this.roleId = this.$route.query.roleId;
    this.getRoleMenu(this.roleId);
  },
  methods: {
    // 获取所有菜单
    treeList() {
      getLeftMenuAll().then((res) => {
        if (res.status === 1) {
          this.menuTreeList = res.data;
        }
      });
    },
    // 根据角色ID，获取当前角色拥有的菜单
    getRoleMenu(roleId) {
      getRoleMenuWithId({ id: roleId }).then((res) => {
        if (res.status == 1) {
          let menusIds = res.data.menus;
          let checkedMenusIds = [];
          if (menusIds !== null && menusIds !== undefined && menusIds !== "") {
            checkedMenusIds = menusIds.split(",");
          }
          // console.log(checkedMenusIds);
          this.$refs.tree.setCheckedKeys(checkedMenusIds);
        }
      });
    },
    // 点击保存
    handleSave() {
      // 获取选中的菜单
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let checkedMenuIds = new Set(); // Set也是一个容器，保存的数据不能重复
      if (checkedNodes !== null && checkedNodes.length > 0) {
        for (let i = 0; i < checkedNodes.length; i++) {
          let checkedNode = checkedNodes[i];
          checkedMenuIds.add(checkedNode.id);
        }
      }
      let menuArr = Array.from(checkedMenuIds);
      let menuStr = menuArr.join(",");

      this.$confirm("是否分配菜单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
            editRoleMenuWithId({ id: this.roleId, menus: menuStr }).then((res) => {
              if (res.status === 1) {
                this.$message({
                  type: "success",
                  message: "分配菜单成功",
                });
                this.$router.back()
              } else {
                this.$message.error("分配菜单失败");
              }
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消分配",
          });
        });
    },
    // 点击清空
    handleClear() {
      this.$refs.tree.setCheckedKeys([]);
    },
  },
};
</script>

<style>
</style>